/**
 * 重金属数据实现类
 */
package com.sc.datacollect.imple;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sc.datacollect.util.Common;
import com.sc.datacollect.util.DateFormatUtils;
import com.sc.datacollect.util.MongoDb;
import com.sc.datacollect.util.SiteUtil;
import com.sc.datacollect.util.UnifiedCodePo;
import com.sc.datacollect.util.UnifiedcodeUtil;

public class OCEC implements IProtocol {
	
	private JSONArray data;
	private MongoDb mongodb;

	public OCEC(String dstype, String datasource, String datatype, JSONArray data, MongoDb mongodb) {
		this.data = data;
		this.mongodb = mongodb;
	}

	@Override
	public void initData() {
	}
	
	public String saveData() {
		try {
			for(int i = 0; i < data.size(); i++) {
				// 格式化时间
				JSONObject o = data.getJSONObject(i);
				String dateStr = String.valueOf(o.get("startDateTime"));
				try {
					dateStr = DateFormatUtils.getDate_str(DateFormatUtils.getDate_util(dateStr), 2).substring(0, 13) + ":00:00";
				} catch (Exception e) {}
				
				o.put("monitorTime", dateStr);
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				o.put("createTime", sdf.format(new Date()));
				
				List<UnifiedCodePo> pos = new LinkedList<UnifiedCodePo>();
				UnifiedCodePo po = null;
				for (String key : o.keySet()) {
					po = new UnifiedCodePo();
					po.setInCode(key);
					po.setCatalogCode("ITP_OCEC");
					pos.add(po);
				}
				// 调用编码转换
				pos = UnifiedcodeUtil.convert(pos);
				JSONObject convertObj = new JSONObject();
				for (String key : o.keySet()) {
					String myCode = UnifiedcodeUtil.getMyCode(pos, key);
					
					convertObj.put(myCode, o.get(key));
				}
				
				// 添加站点名称
				convertObj.put("siteName", SiteUtil.getSiteName(convertObj.getString("siteCode"), dateStr));
				
//				System.out.println(convertObj);
				mongodb.insert("ORI_ITP_OCEC_HOUR-" + dateStr.substring(0, 4), JSON.toJSONString(convertObj));
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
			return Common.EXCEPTIONCODE;
		}
		return Common.SUCCESSCODE;
	}

}
